#!/usr/bin/perl -w # useful for syntax highlighting
package clreqd_modules;

use strict;
use lvm;
use Data::Dumper;
use cldb;

sub ss_set_sync_rate {
my %ARGS=@_;
my $vgname=$ARGS{VGNAME};
my $lvname=$ARGS{LVNAME};
my $application=$ARGS{APPLICATION};
my $rate=$ARGS{RATE};

	my $perm=0;
	if(defined($ARGS{PERM}) && to_bool($ARGS{PERM})) {
		$perm=1;
	}

	#################################################################
	# Get the storage type from config db.				#
	#################################################################
	my $CLDB=new cldb("$::ENV{TRUECL_CFG}/config.db");
	if(!defined($CLDB)) {
		return "ERROR Unable to connect to 'config' database.";
	}
	my $res=$CLDB->get_rows("SELECT * FROM applications WHERE name = '$application';");
	if(!defined($res->[0]->{nodes})) {
		return "ERROR Application '$application' is unknown.";
	}

	$CLDB->disconnect; $CLDB=undef;
	my $s=$res->[0]->{storage};
	#################################################################
	# Now open open the configuration database to get the storage	#
	# spec and list of volume groups...				#
	#################################################################

	if(! -f "$::ENV{TRUECL_CODE}/lib/storage_spec/$s.pm") {
		return "ERROR - Storage spec '$s' not available.";
	}

	eval "use storage_spec::$s;";
	my $STORAGE=eval "new storage_spec::$s;";
	if(!defined($STORAGE)) {
		return "ERROR Unable to use storage spec - storage_spec::$s\nError: " . eval "storage_spec::${s}::get_error_msg;";
	}
	#################################################################
	# If VGNAME == "$$ALL" then we run against all vgs and LV's.	#
	#################################################################

	my @VGLIST=($vgname);
	if($vgname eq '$$ALL') {
		my $VGS=$res->[0]->{vgs};
		@VGLIST=split(/,/,$VGS);
	}
	
	#################################################################
	# We need to run against each vg separately.			#
	#################################################################
	my ($rc,$info);
	for my $VG (@VGLIST) {
		if($perm) {
			($rc,$info)=$STORAGE->set_sync_rate($VG,$lvname,$application,$rate,$perm);
		} else {
			($rc,$info)=$STORAGE->set_sync_rate($VG,$lvname,$application,$rate);
		}
		last if $rc;
	}

	if(!$rc) {
		return "OK";
	}
	if($rc==1) {
		return "ERROR $info";
	}
	return "ERROR Action not supported on this storage type.";
}

1;
